<template>
	<view>
		<u-modal v-model="show" z-index="2000" :content="content" :show-cancel-button="true" @confirm="gouser">
		</u-modal>
		<view class="head">
			<view class="topIcon">
				<!-- <view class="iconfont">&#xe613;</view> -->
				<u-icon name="email" :class="hasIsRead ? 'animated swing iconfont spc' : 'iconfont spc'" color="#fff"
					size="45" @tap="goMessage"></u-icon>
				<view v-if="hasIsRead">
					<u-badge class="badge" :count="idx" style="margin-top: 25px"></u-badge>
				</view>
			</view>
			<view class="flex spc" style="margin: 100upx 0 0 40upx">
				<image src="../../static/img/oldboy.png" mode="aspectFit" style="
            width: 120upx;
            height: 120upx;
            background-size: cover;
            margin-right: 50upx;
            border-radius: 50%;
          " class="spc" v-show="user.userType == '4' && user.gender == '1'"></image>
				<image src="../../static/img/oldgirl.png" mode="aspectFit" style="
            width: 120upx;
            height: 120upx;
            margin-right: 50upx;
            border-radius: 50%;
          " class="spc" v-show="user.userType == '4' && user.gender == '0'"></image>
				<image src="../../static/img/babyboy.png" mode="aspectFit" style="
            width: 120upx;
            height: 120upx;
            margin-right: 50upx;
            border-radius: 50%;
          " class="spc" v-show="user.userType == '1' && user.gender == '1'"></image>
				<image src="../../static/img/babygirl.png" mode="aspectFit" style="
            width: 120upx;
            height: 120upx;
            margin-right: 50upx;
            border-radius: 50%;
          " class="spc" v-show="user.userType == '1' && user.gender == '0'"></image>
				<image src="../../static/img/man.png" mode="aspectFit" style="
            width: 120upx;
            height: 120upx;
            margin-right: 50upx;
            border-radius: 50%;
          " class="spc" v-show="user.userType == '3' && user.gender == '1'"></image>
				<image src="../../static/img/woman.png" mode="aspectFit" style="
            width: 120upx;
            height: 120upx;
            margin-right: 50upx;
            border-radius: 50%;
          " class="spc" v-show="user.userType == '3' && user.gender == '0'"></image>
				<image src="../../static/img/woman.png" mode="aspectFit" style="
            width: 120upx;
            height: 120upx;
            margin-right: 50upx;
            border-radius: 50%;
          " class="spc" v-show="user.userType == '2' && user.gender == '0'"></image>
				<view class="spc">
					<view style="color: #fff" class="spc">
						{{ user.userName || "无" }}
						<!-- <text style="display: inline-block; margin: 0 30upx">{{ user.age }}岁</text> -->
						<text v-if="user.userType == '1'" style="display: inline-block; margin-left: 30upx"
							class="spc">{{ monthage }}<span style="margin-right: 20rpx"></span>
						</text>
						<text class="tag" style="
                display: inline-block;
                margin-left: 10upx;
                margin-right: 10rpx;
              ">
							{{ user.userType | userType }}
						</text>
						<text class="tag" style="
                display: inline-block;
                margin-left: 10upx;
                margin-right: 10rpx;
              " v-show="user.userType == 4 || user.chronic == 1">
							慢性病
						</text>
						<text class="tag" v-if="user.userType == '2'"
							style="display: inline-block; margin-right: 30upx">孕{{ user.pregnancy }}周</text>
					</view>
					<view class="ulist flex spc">
						<view class="ulist-scroll spc">
							<view class="uitem-box spc" :style="jslength">
								<view class="uitem spc" v-for="v in familyList" :key="v.id" @tap="swichUser(v)">
									<!-- <image class="userImg spc" src="../../static/img/cat1.png" mode="aspectFit"></image> -->
									<image src="../../static/img/oldboy.png" mode="aspectFit" class="userImg spc"
										v-show="
                      v.appUserInfo.userType == '4' &&
                      v.appUserInfo.gender == '1'
                    "></image>
									<image src="../../static/img/oldgirl.png" mode="aspectFit" class="userImg spc"
										v-show="
                      v.appUserInfo.userType == '4' &&
                      v.appUserInfo.gender == '0'
                    "></image>
									<image src="../../static/img/babyboy.png" mode="aspectFit" class="userImg spc"
										v-show="
                      v.appUserInfo.userType == '1' &&
                      v.appUserInfo.gender == '1'
                    "></image>
									<image src="../../static/img/babygirl.png" mode="aspectFit" class="userImg spc"
										v-show="
                      v.appUserInfo.userType == '1' &&
                      v.appUserInfo.gender == '0'
                    "></image>
									<image src="../../static/img/man.png" mode="aspectFit" class="userImg spc" v-show="
                      v.appUserInfo.userType == '3' &&
                      v.appUserInfo.gender == '1'
                    "></image>
									<image src="../../static/img/woman.png" mode="aspectFit" class="userImg spc" v-show="
                      v.appUserInfo.userType == '3' &&
                      v.appUserInfo.gender == '0'
                    "></image>
									<image src="../../static/img/woman.png" mode="aspectFit" class="userImg spc" v-show="
                      v.appUserInfo.userType == '2' &&
                      v.appUserInfo.gender == '0'
                    "></image>
									<view style="font-size: 24upx; color: #fff" class="spc">
										{{ v.appUserInfo.userName }}
									</view>
								</view>
								<!-- <view class="uitem" @tap="goSubInfo"> -->
								<view class="uitem spc" @tap="goAddUser">
									<image class="userImg spc" src="../../static/img/plus-circle.png" mode="aspectFit"
										style="height: 60upx"></image>
									<view style="font-size: 24upx; color: #fff" class="spc">新增</view>
								</view>
							</view>
						</view>
						<view class="tipsss" v-if="user.userType == 1 && familyList.length <= 0">官方提醒：方便信息维护，请您尽快完善监护人信息
						</view>
					</view>
				</view>
			</view>
		</view>
		<view style="height: 350upx"></view>

		<!-- 信封条 -->
		<view style="
        width: 98%;
        height: 20upx;
        background-color: #028a9e;
        position: fixed;
        margin: 0 1% 0;
        z-index: 2;
        box-sizing: border-box;
        border-radius: 6upx;
      " class="spd"></view>
		<view class="letter-box" :class="{ close: isCloseLetter }" v-if="user.userType != 3">
			<view class="letter-list flex flex-j-a">
				<!-- <view class="letter-item" v-for="(v,index) in letterList" :key="index" @tap="goUrl(v)">
					<image class="icon" :src="v.icon" mode=""></image>
					<view class="tit">{{v.name}}</view>
				</view> -->
				<view class="letter-item" v-for="(v, index) in cardList" :key="index" @tap="goUrl(v)">
					<image class="icon animated flipInX" :src="v.iconUrl || '../../static/img/home-card1.png'" mode="">
					</image>
					<view class="tit">{{ v.name }}</view>
				</view>
			</view>
			<view class="closeBtn flex flex-al-c" @tap="closeLetter">
				<view class="iconfont" :class="{
            'iconarrow-down-s-fill': isCloseLetter,
            iconarrowup: !isCloseLetter,
          }">
				</view>{{ isCloseLetter ? "展开" : "收起" }}
			</view>
		</view>
		<view class="letter-box" :class="{ close: isCloseLetter }" :style="{
        height: user.userType == '3' && isCloseLetter ? '25px' : '125px',
      }" v-if="user.userType == 3">
			<view class="letter-list flex flex-j-a">
				<!-- <view class="letter-item" v-for="(v,index) in letterList" :key="index" @tap="goUrl(v)">
					<image class="icon" :src="v.icon" mode=""></image>
					<view class="tit">{{v.name}}</view>
				</view> -->
				<view class="letter-item" v-for="(v, index) in cardList" :key="index" @tap="goUrl(v)">
					<image class="icon" :src="v.iconUrl || '../../static/img/home-card1.png'" mode=""></image>
					<view class="tit">{{ v.name }}</view>
				</view>
			</view>
			<view class="closeBtn flex flex-al-c" @tap="closeLetter">
				<view class="iconfont" :class="{
            'iconarrow-down-s-fill': isCloseLetter,
            iconarrowup: !isCloseLetter,
          }">
				</view>{{ isCloseLetter ? "展开" : "收起" }}
			</view>
		</view>
		<view :style="{ height: isCloseLetter ? '50upx' : '350upx' }" v-if="user.userType != 3"></view>
		<view :style="{ height: isCloseLetter ? '50upx' : '300upx' }" v-if="user.userType == 3"></view>
		<u-modal v-model="showAddFamilyType" ref="uModal" :mask-close-able="true" :async-close="true" title="请选择"
			:show-confirm-button="false">
			<view>
				<view class="uni-item-line"></view>
				<!-- <view class="uni-item-line" style="padding: 30upx 0; color: #007aff; text-align: center" @tap="goFamilyList">从家庭成员列表选择</view> -->
				<view style="padding: 30upx 0; color: #007aff; text-align: center" @tap="goAddUser">重新添加</view>
			</view>
		</u-modal>
	</view>
</template>

<script>
	import WebsocketHeartbeatJs from "@/utils/index1.js";
	export default {
		data() {
			return {
				show: false,
				content: "是否切换用户",
				cont: "",
				showAddFamilyType: false,
				user: {},
				birthday: "",
				monthage: "",
				timer: null,
				isCloseLetter: false,
				idx: "", //获取未读消息条数
				idx1: "", //外部icon 条数
				letterList: [{
						icon: "../../static/img/home-card1.png",
						name: "待办事项",
						url: "/pages/main/child/backlog/backlog-tab",
					},
					{
						icon: "../../static/img/home-card1.png",
						name: "健康建议",
						url: "/pages/main/child/backlog/suggest",
					},
					{
						icon: "../../static/img/home-card1.png",
						name: "预约检查",
						url: "",
					},
					{
						icon: "../../static/img/home-card1.png",
						name: "接种计划",
						url: "/pages/main/child/backlog/inoculate",
					},
					{
						icon: "../../static/img/home-card1.png",
						name: "儿童保健",
						url: "/pages/main/child/backlog/plan",
					},
					{
						icon: "../../static/img/home-card1.png",
						name: "成长曲线",
						url: "/pages/main/child/backlog/grow-graph",
					},
				],
				familyList: [], // 家庭
				tapLetter: false,
				hasIsRead: false, //是否有个人未读消息
			};
		},
		props: ["cardList"],
		filters: {
			userType(inp) {
				let str = "";
				if (inp == 1) str = "儿童";
				if (inp == 2) str = "孕妇";
				if (inp == 3) str = "普通人";
				if (inp == 4) str = "老年人";
				return str;
			},
		},
		computed: {
			jslength() {
				let size = (this.familyList.length + 1) * 55;
				return {
					width: size + "px",
				};
			},
			// getAge() {
			// 	if (this.birthday != null) {
			// 		var usedTime =
			// 			Date.parse(new Date()) - Date.parse(new Date(this.birthday));
			// 		var days = Math.floor(usedTime / (24 * 3600 * 1000));
			// 		var time =
			// 			Math.floor(days / 365) +
			// 			"岁" +
			// 			Math.floor((days % 365) / 30) +
			// 			"月龄";
			// 		return time;
			// 	} else {
			// 		return "暂无记录";
			// 	}
			// },
		},
		methods: {
			//websocket 获取角标and邮件角标
			contentWebsock() {
				const userInfo = uni.getStorageSync("user");
				this.user.id = userInfo.id;
				const URL = this.config.finIp();
				const userId = this.user.id;
				var socketUrl = URL + "/iconNum/" + userId + "Icon";
				socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");
				console.log(socketUrl);
				const options = {
					url: socketUrl,
					pingTimeout: 20000,
					pongTimeout: 15000,
					reconnectTimeout: 2000,
					pingMsg: "heartbeat",
				};
				const self = this;
				const socket = new WebsocketHeartbeatJs(options);

				//打开事件
				socket.onopen = function() {
					// console.log("websocket已打开");
					//socket.send("这是来自客户端的消息" + location.href + new Date());
				};
				//获得消息事件

				socket.onmessage = function(msg) {
					// console.log(msg);
					// //发现消息进入    开始处理前端触发逻辑
					if (msg.data != "heartbeat") {
						self.initHasIsRead();
						//把接收的值传入Vue data中
						// console.log(msg.data)
						if (msg.data.msgNum >= 1) {
							uni.setStorageSync("msgFlag", 1);
							this.idx1 = msg.data.msgNum;
							let msgNum = uni.getStorageSync("firstMsgNum");
							if (msgNum == null) {
								uni.setStorageSync("firstMsgNum", this.idx1);
								plus.runtime.setBadgeNumber(msg.data.msgNum);
							} else {
								if (msgNum != this.idx1) {
									uni.setStorageSync("firstMsgNum", this.idx1);
									plus.runtime.setBadgeNumber(msg.data.msgNum);
								}
							}
						} else {
							this.idx1 = 0;
							let flag = uni.getStorageSync("msgFlag");
							if (flag == 1 || flag == "") {
								uni.setStorageSync("firstMsgNum", 0);
								uni.setStorageSync("msgFlag", 0);
								// plus.runtime.setBadgeNumber(3);
								if (plus.os.name.toLowerCase() == "ios") {
									//导入ios UIApplication
									var UIApplication = plus.ios.import("UIApplication");
									var app = UIApplication.sharedApplication();
									//获取应用图标的数量
									// var oldNum = app.applicationIconBadgeNumber();
									// var newNum = oldNum - 1;
									//设置应用图标的数量
									plus.runtime.setBadgeNumber(0);
									//导入个推原生类
									var GeTuiSdk = plus.ios.importClass("GeTuiSdk");
									GeTuiSdk.setBadge(0);
								}
							}
						}
					}
				};
				//关闭事件
				socket.onclose = function() {
					// console.log("websocket已关闭");
				};
				//发生了错误事件
				socket.onerror = function() {
					console.log("websocket发生了错误");
				};
			},
			getAge() {
				this.config
					.get("/family/switchUserAge", {
						userId: this.user.id,
					})
					.then((res) => {
						// console.log(res)
						this.monthage = res.data.msg;
					});
			},
			getSwitchAge() {
				this.config
					.get("/family/switchUserAge", {
						userId: this.cont.appUserInfo.id,
					})
					.then((res) => {
						this.monthage = res.data.msg;
					});
			},
			closeLetter() {
				this.tapLetter = true;
				this.isCloseLetter = !this.isCloseLetter;
			},
			pclose(bool) {
				if (this.tapLetter) {
					this.tapLetter = false;
					return;
				}
				this.isCloseLetter = bool;
			},
			goUrl(v) {
				if (!v.pageUrl) return;
				uni.navigateTo({
					url: v.pageUrl,
				});
			},
			// 去消息列表
			goMessage() {
				uni.navigateTo({
					url: "/pages/main/pub/message-list",
				});
			},
			getFamily() {
				let self = this;
				this.config.post("/family/getFamilyList", {}).then((res) => {
					uni.hideLoading();
					if (res.data.code === 200) {
						res.data.data = res.data.data || [];
						self.familyList = [];
						let results = res.data.data.filter((v) => {
							return v.appUserInfo
						})
						results.forEach((it, v) => {
							if (it.appUserInfo.id != self.user.id) {
								self.familyList.push(it);
							}
						});
					} else {
						if (res.data.code == "-201") {
							self.config.handleError(res.data);
						} else {
							uni.showToast({
								title: self.config.handleError(res.data),
								icon: "none",
							});
						}
					}
				});
			},
			goSubInfo() {
				this.showAddFamilyType = true;
			},
			// 从已有成员选择
			goFamilyList() {
				this.showAddFamilyType = false;
				uni.navigateTo({
					url: "/pages/main/pub/select-family",
				});
			},
			// 重新添加家庭成员
			goAddUser() {
				this.showAddFamilyType = false;
				uni.navigateTo({
					url: "/pages/reg/sub-user-info?subType=1",
				});
			},
			// 切换用户
			swichUser(v) {
				this.cont = v;
				this.show = true;
				uni.setStorageSync("yyState", 1);
			},
			gouser() {
				let self = this;
				/* uni.showLoading({
					title: "加载中",
					mask: true,
				}); */
				setTimeout((s) => {
					uni.hideLoading();
				}, 5000);
				this.config
					.post("/family/switchUser", {
						userId: this.cont.appUserInfo.id,
					})
					.then((res) => {
						uni.hideLoading();
						if (res.data.code === 200) {
							uni.setStorageSync("subsidiary", res.data.msg);
							uni.setStorageSync("token", res.data.msg); //保留登陆用户的状态
							uni.setStorageSync("uerInfo", res.data.msg); //保留登陆用户的状态
							self.config.header.subsidiary = res.data.msg;
							self.getFamily();
							this.getSwitchAge();
							//self.getListInfo();
							// self.$parent.$parent.$refs.newList.getBallInfo()
							// self.$parent.$parent.$refs.newList.getListInfo()
							self.$parent.$refs.newList.getBallInfo();
							self.$parent.$refs.newList.getListInfo();
							self.$emit("reloadServerInfo", "");
							self.sendCid();
						} else {
							uni.showToast({
								title: self.config.handleError(res.data),
								icon: "none",
							});
						}
					});
			},
			sendCid() {
				this.config
					.post("/uni/saveCidToUser", {
						cid: uni.getStorageSync("cid"),
						ptType: uni.getStorageSync("device"),
					})
					.then((res) => {
						console.log(res);
					});
			},
			initHasIsRead() {
				let self = this;
				/* uni.showLoading({
					title: "加载中",
					mask: true,
				}); */
				setTimeout((s) => {
					uni.hideLoading();
				}, 5000);
				this.config.post("/message/initPersonOwnMsgList", {}).then((res) => {
					if (res.data.code === 200) {
						if (res.data.data && res.data.data.length > 0) {
							this.hasIsRead = true;
							this.idx = res.data.data.length;
						} else {
							this.hasIsRead = false;
						}
					} else {
						if (res.data.code == "-201") {
							self.config.handleError(res.data);
						} else {
							uni.showToast({
								title: self.config.handleError(res.data),
								icon: "none",
							});
						}
						// uni.navigateTo({
						// 	url: '/pages/login/login2'
						// })
					}
				});
			},
			timeUp() {
				clearInterval(this.timer);
			},
		},
		mounted() {
			this.user = this.config.globalData.user;
			console.log(this.config.globalData.user);
			uni.$on("user", (bool) => {
				this.user = this.config.globalData.user;
				this.birthday = this.user.birthday;
				this.$store.state.birthday = this.birthday;
				this.getAge();
			});
			// this.contentWebsock();   关闭websocket
			this.getFamily();
		},
		onShow() {
			this.getFamily();
			// this.contentWebsock();   关闭websocket
		},
	};
</script>

<style lang="less" scoped>
	.tipsss {
		font-size: 10px;
		color: rgb(238, 238, 238);
		margin-top: 0px;
		width: 610rpx;
		left: 120rpx;
		bottom: 50rpx;
		position: absolute;
	}

	.head {
		position: fixed;
		width: 100%;
		height: 395upx;
		background-color: #18c7e1;
		padding-top: 1upx;
		z-index: 1;

		.topIcon {
			position: relative;
			width: 100%;

			.iconfont {
				position: absolute;
				top: 80upx;
				right: 30upx;
				color: #eee;
			}

			.badge {
				position: absolute;
			}
		}

		.tag {
			padding: 0 20upx;
			background-color: #fff;
			color: #18c7e1;
			font-size: 20upx;
			border-radius: 20upx;
		}

		.ulist {
			margin-top: 30upx;

			.ulist-scroll {
				// display: flex;
				max-width: 400rpx;
				height: 105rpx;
				margin-right: 10upx;
				overflow-x: scroll;
				overflow-y: hidden;
				display: inline;

				.uitem-box {
					// width: 1000rpx;
					height: 100rpx;
					// width: 900up
				}
			}

			.uitem {
				display: inline-block;
				margin-right: 10upx;
				font-size: 20upx;
				text-align: center;

				.userImg {
					width: 60upx;
					height: 60upx;
					margin-right: 30upx;
					margin: 0;
				}
			}
		}
	}

	//  信封
	.letter-box {
		width: 96%;
		margin: 10upx 2% 0;
		position: fixed;
		overflow-y: hidden;
		height: 350upx;
		background-color: #fff;
		box-shadow: 0 0 30upx 0 #ccc;
		border-bottom-left-radius: 10upx;
		border-bottom-right-radius: 10upx;
		transition: height 0.2s linear;
		z-index: 2;
	}

	.letter-box.close {
		height: 44upx;
	}

	.letter-list {
		position: absolute;
		width: 100%;
		bottom: 30upx;
		left: 0;
		bottom: 50upx;
		flex-wrap: wrap;

		.letter-item {
			width: 30%;
			text-align: center;
			padding: 30upx 0;

			.icon {
				width: 50upx;
				height: 50upx;
			}

			.tit {
				font-size: 24upx;
			}
		}
	}

	.closeBtn {
		position: absolute;
		width: 100%;
		left: 0;
		bottom: 0;
		font-size: 24upx;
		color: #ccc;
		justify-content: center;
	}
</style>
<style scoped>
	@media (prefers-color-scheme: closedark) {

		//  黑暗模式
		* {
			background-color: #000000 !important;
			color: #ffffff !important;
		}

		.icon {
			background-color: #2a2a2c !important;
		}

		.tit {
			background-color: #2a2a2c !important;
		}

		.head {
			background-color: #1b1c1e !important;
		}

		.spc {
			background-color: #1b1c1e !important;
		}

		//信封条
		.spd {
			background-color: #38383c !important;
		}

		.uitem {
			background-color: #1b1c1e !important;
		}

		.letter-box {
			background-color: #2a2a2c !important;
		}

		.flex-j-a {
			background-color: #2a2a2c !important;
		}

		.closeBtn {
			background-color: #2a2a2c !important;
		}

		.iconfont {
			background-color: #2a2a2c !important;
		}

		uni-view.letter-item {
			background-color: #2a2a2c !important;
			
			.tit {
				background-color: #2a2a2c !important;
			}

			.icon {
				background-color: #2a2a2c !important;
			}
		}
	}
</style>
